var tgd = tgd || {};
tgd.Utilities = tgd.Utilities || {};
tgd.Utilities.Calendar = tgd.Utilities.Calendar || {};
tgd.Utilities.Calendar.Views = tgd.Utilities.Calendar.Views || {};

tgd.Utilities.Calendar.Views.MonthPicker = function (canvas, year, month) {
	this._canvas = canvas;
	this._year = year;
	this._month = month;
	this.onMonthChanged = null;
	this._btnPrev = document.createElement("span");
	this._btnNext = document.createElement("span");
	this._monthDisplay = document.createElement("select");
	this._yearDisplay = document.createElement("span");

	var self = this;

	this._yearDisplay.className = "year";
	this._monthDisplay.className = "month";

	for (var i = 0; i < 12; ++i) {
		var opt = document.createElement("option");
		opt.text = tgd.Utilities.Calendar.MonthNames[i];
		opt.value = i;
		this._monthDisplay.options[i] = opt;
	}

	this._yearDisplay.innerHTML = this._year;
	this._monthDisplay.options[this._month].selected = true;

	this._monthDisplay.onchange = function() {
		self._month = self._monthDisplay.selectedIndex;

		if (self.onMonthChanged) {
			self.onMonthChanged();
		}
	}

	/* SETUP PREVIOUS MONTH BUTTON */
	this._btnPrev.innerHTML = "&laquo;";
	this._btnPrev.className = "button previous";
	this._btnPrev.onclick = function() {
		self._monthDisplay.options[self._month = ((self._month + 11) % 12)].selected = true;

		if (self._month == 11) {  //previous year
			self._yearDisplay.innerHTML = --self._year;
		}

		if (self.onMonthChanged) {
			self.onMonthChanged();
		}
	};

	/* SETUP NEXT MONTH BUTTON */
	this._btnNext.innerHTML = "&raquo;";
	this._btnNext.className = "button next";
	this._btnNext.onclick = function() {
		self._monthDisplay.options[self._month = (++self._month % 12)].selected = true;

		if (self._month == 0) {  //next year
			self._yearDisplay.innerHTML = ++self._year;
		}

		if (self.onMonthChanged) {
			self.onMonthChanged();
		}
	};

	/* ADD DOM ELEMENTS TO CANVAS */
	this._canvas.appendChild(this._btnPrev);
	this._canvas.appendChild(this._monthDisplay);
	this._canvas.appendChild(this._yearDisplay);
	this._canvas.appendChild(this._btnNext);

	if (tgd.Utilities.Calendar.Views.MonthPicker._initialized === undefined) {

		tgd.Utilities.Calendar.Views.MonthPicker.prototype.getYear = function() {
			return this._year;
		}

		tgd.Utilities.Calendar.Views.MonthPicker.prototype.getMonth = function() {
			return this._month;
		}

		tgd.Utilities.Calendar.Views.MonthPicker.prototype.setMonth = function(y, m) {
			this._year = y;
			this._month = m;
			this._yearDisplay.innerHTML = this._year;
			this._monthDisplay.options[this._month].selected = true;
		}		

		tgd.Utilities.Calendar.Views.MonthPicker._initialized = true;
	}
}
